/**
 * @author SongJun
 * @description 简单二分查找
 * @date 2021/9/10 17:54
 */
public class BinarySearch {
    public static void main(String[] args) {
        BinarySearch instance = new BinarySearch();
        int[] nums = {-3,1,3,5,6,8,20};
        int target = 1;
        System.out.println(instance.search(nums, target));
    }

    public int search(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;
        while(left <= right){
            int middle = (left+right)/2;
            if(nums[middle] == target){
                return middle;
            } else if(nums[middle] > target){
                right = middle-1;
            } else if(nums[middle] < target){
                left = middle + 1;
            }
        }
        return -1;
    }

    public int[] searchHeadTail(int[] nums, int target) {
        int[] ret = {-1, -1};
        int left = 0;
        int right = nums.length - 1;
        while(left <= right){
            int middle = (left+right)/2;
            if(nums[middle] == target){
                ret[0] = middle;
                ret[1] = middle;
            } else if(nums[middle] > target){
                right = middle-1;
            } else if(nums[middle] < target){
                left = middle + 1;
            }
        }
        return ret;
    }
}
